# -*- coding: utf-8 -*-
"""
日志管理界面
"""
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
                            QLabel, QPushButton, QTableWidget, QTableWidgetItem,
                            QHeaderView, QMessageBox, QGroupBox, QComboBox,
                            QDateEdit, QCheckBox, QTextEdit, QSplitter)
from PyQt5.QtCore import Qt, QDate
from PyQt5.QtGui import QFont
from core.export_manager import ExportManager
from datetime import datetime, timedelta
import os

class LogWidget(QWidget):
    """日志管理界面"""
    
    def __init__(self, export_manager: ExportManager):
        super().__init__()
        self.export_manager = export_manager
        self.logs = []
        
        self.init_ui()
        self.refresh_logs()
    
    def init_ui(self):
        """初始化界面"""
        layout = QVBoxLayout(self)
        
        # 筛选条件组
        filter_group = QGroupBox("筛选条件")
        filter_layout = QGridLayout(filter_group)
        
        # 日期范围
        filter_layout.addWidget(QLabel("开始日期:"), 0, 0)
        self.start_date = QDateEdit()
        self.start_date.setDate(QDate.currentDate().addDays(-30))
        self.start_date.setCalendarPopup(True)
        filter_layout.addWidget(self.start_date, 0, 1)
        
        filter_layout.addWidget(QLabel("结束日期:"), 0, 2)
        self.end_date = QDateEdit()
        self.end_date.setDate(QDate.currentDate())
        self.end_date.setCalendarPopup(True)
        filter_layout.addWidget(self.end_date, 0, 3)
        
        # 导出结果
        filter_layout.addWidget(QLabel("导出结果:"), 1, 0)
        self.result_combo = QComboBox()
        self.result_combo.addItem("全部", "")
        self.result_combo.addItem("成功", "成功")
        self.result_combo.addItem("失败", "失败")
        filter_layout.addWidget(self.result_combo, 1, 1)
        
        # 导出格式
        filter_layout.addWidget(QLabel("导出格式:"), 1, 2)
        self.format_combo = QComboBox()
        self.format_combo.addItem("全部", "")
        self.format_combo.addItem("Excel", "Excel")
        self.format_combo.addItem("Word", "Word")
        self.format_combo.addItem("Markdown", "Markdown")
        filter_layout.addWidget(self.format_combo, 1, 3)
        
        # 筛选按钮
        self.filter_button = QPushButton("筛选")
        self.filter_button.clicked.connect(self.filter_logs)
        filter_layout.addWidget(self.filter_button, 2, 0)
        
        # 刷新按钮
        self.refresh_button = QPushButton("刷新")
        self.refresh_button.clicked.connect(self.refresh_logs)
        filter_layout.addWidget(self.refresh_button, 2, 1)
        
        # 清空日志按钮
        self.clear_button = QPushButton("清空日志")
        self.clear_button.clicked.connect(self.clear_logs)
        filter_layout.addWidget(self.clear_button, 2, 2)
        
        layout.addWidget(filter_group)
        
        # 创建分割器
        splitter = QSplitter(Qt.Horizontal)
        layout.addWidget(splitter)
        
        # 左侧：日志列表
        self.create_log_table(splitter)
        
        # 右侧：日志详情
        self.create_log_detail(splitter)
        
        # 设置分割器比例
        splitter.setSizes([600, 400])
    
    def create_log_table(self, parent):
        """创建日志表格"""
        table_widget = QWidget()
        table_layout = QVBoxLayout(table_widget)
        
        # 日志列表组
        log_group = QGroupBox("导出日志")
        log_group_layout = QVBoxLayout(log_group)
        
        # 创建表格
        self.log_table = QTableWidget()
        self.log_table.setColumnCount(8)
        self.log_table.setHorizontalHeaderLabels([
            "导出时间", "数据库名", "表数量", "导出格式", 
            "文件名", "导出结果", "错误信息", "操作"
        ])
        
        # 设置表格属性
        self.log_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.log_table.setAlternatingRowColors(True)
        self.log_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.log_table.setSelectionMode(QTableWidget.SingleSelection)
        
        # 连接选择变化信号
        self.log_table.itemSelectionChanged.connect(self.on_log_selection_changed)
        
        log_group_layout.addWidget(self.log_table)
        table_layout.addWidget(log_group)
        parent.addWidget(table_widget)
    
    def create_log_detail(self, parent):
        """创建日志详情区域"""
        detail_widget = QWidget()
        detail_layout = QVBoxLayout(detail_widget)
        
        # 日志详情组
        detail_group = QGroupBox("日志详情")
        detail_group_layout = QVBoxLayout(detail_group)
        
        # 详情信息
        self.detail_text = QTextEdit()
        self.detail_text.setReadOnly(True)
        self.detail_text.setPlaceholderText("请选择一条日志记录查看详情")
        detail_group_layout.addWidget(self.detail_text)
        
        # 操作按钮
        button_layout = QHBoxLayout()
        
        self.open_file_button = QPushButton("打开文件")
        self.open_file_button.clicked.connect(self.open_export_file)
        self.open_file_button.setEnabled(False)
        button_layout.addWidget(self.open_file_button)
        
        self.open_folder_button = QPushButton("打开文件夹")
        self.open_folder_button.clicked.connect(self.open_export_folder)
        self.open_folder_button.setEnabled(False)
        button_layout.addWidget(self.open_folder_button)
        
        detail_group_layout.addLayout(button_layout)
        detail_layout.addWidget(detail_group)
        parent.addWidget(detail_widget)
    
    def refresh_logs(self):
        """刷新日志列表"""
        try:
            # 获取日志数据
            self.logs = self.export_manager.get_export_logs(1000)
            
            # 更新表格
            self.update_log_table(self.logs)
            
        except Exception as e:
            QMessageBox.critical(self, "刷新失败", f"刷新日志失败:\n{str(e)}")
    
    def filter_logs(self):
        """筛选日志"""
        try:
            # 获取筛选条件
            start_date = self.start_date.date().toPyDate()
            end_date = self.end_date.date().toPyDate()
            result_filter = self.result_combo.currentData()
            format_filter = self.format_combo.currentData()
            
            # 筛选日志
            filtered_logs = []
            for log in self.logs:
                # 日期筛选
                log_date = datetime.strptime(log['export_time'], '%Y-%m-%d %H:%M:%S').date()
                if log_date < start_date or log_date > end_date:
                    continue
                
                # 结果筛选
                if result_filter and log['export_result'] != result_filter:
                    continue
                
                # 格式筛选
                if format_filter and log['export_format'] != format_filter:
                    continue
                
                filtered_logs.append(log)
            
            # 更新表格
            self.update_log_table(filtered_logs)
            
        except Exception as e:
            QMessageBox.critical(self, "筛选失败", f"筛选日志失败:\n{str(e)}")
    
    def update_log_table(self, logs: list):
        """更新日志表格"""
        self.log_table.setRowCount(len(logs))
        
        for row, log in enumerate(logs):
            # 导出时间
            self.log_table.setItem(row, 0, QTableWidgetItem(log['export_time']))
            
            # 数据库名
            self.log_table.setItem(row, 1, QTableWidgetItem(log['database_name']))
            
            # 表数量
            self.log_table.setItem(row, 2, QTableWidgetItem(str(log['table_count'])))
            
            # 导出格式
            self.log_table.setItem(row, 3, QTableWidgetItem(log['export_format']))
            
            # 文件名
            self.log_table.setItem(row, 4, QTableWidgetItem(log['file_name']))
            
            # 导出结果
            result_item = QTableWidgetItem(log['export_result'])
            if log['export_result'] == '成功':
                result_item.setBackground(Qt.green)
            else:
                result_item.setBackground(Qt.red)
            self.log_table.setItem(row, 5, result_item)
            
            # 错误信息
            error_msg = log.get('error_message', '')
            if error_msg:
                error_item = QTableWidgetItem(error_msg[:50] + "..." if len(error_msg) > 50 else error_msg)
                error_item.setToolTip(error_msg)
            else:
                error_item = QTableWidgetItem("")
            self.log_table.setItem(row, 6, error_item)
            
            # 操作按钮
            action_button = QPushButton("查看")
            action_button.clicked.connect(lambda checked, r=row: self.view_log_detail(r))
            self.log_table.setCellWidget(row, 7, action_button)
    
    def on_log_selection_changed(self):
        """日志选择变化"""
        current_row = self.log_table.currentRow()
        if current_row >= 0 and current_row < len(self.logs):
            log = self.logs[current_row]
            
            # 更新详情
            self.update_log_detail(log)
            
            # 启用操作按钮
            self.open_file_button.setEnabled(log['export_result'] == '成功')
            self.open_folder_button.setEnabled(True)
        else:
            # 清空详情
            self.detail_text.clear()
            self.detail_text.setPlaceholderText("请选择一条日志记录查看详情")
            
            # 禁用操作按钮
            self.open_file_button.setEnabled(False)
            self.open_folder_button.setEnabled(False)
    
    def view_log_detail(self, row: int):
        """查看日志详情"""
        if row >= 0 and row < len(self.logs):
            log = self.logs[row]
            self.update_log_detail(log)
            self.log_table.selectRow(row)
    
    def update_log_detail(self, log: dict):
        """更新日志详情"""
        detail_info = f"""导出详情:
导出时间: {log['export_time']}
数据库名称: {log['database_name']}
表数量: {log['table_count']}
导出格式: {log['export_format']}
文件路径: {log['file_path']}
文件名: {log['file_name']}
导出结果: {log['export_result']}"""
        
        if log.get('error_message'):
            detail_info += f"\n错误信息: {log['error_message']}"
        
        self.detail_text.setText(detail_info)
    
    def _get_file_extension(self, export_format: str) -> str:
        """获取文件扩展名"""
        extensions = {
            'Excel': '.xlsx',
            'Word': '.docx',
            'Markdown': '.md'
        }
        return extensions.get(export_format, '')
    
    def open_export_file(self):
        """打开导出文件"""
        current_row = self.log_table.currentRow()
        if current_row >= 0 and current_row < len(self.logs):
            log = self.logs[current_row]
            if log['export_result'] == '成功':
                # 构建完整文件路径（文件名现在已包含扩展名）
                file_path = os.path.join(log['file_path'], log['file_name'])
                
                if os.path.exists(file_path):
                    os.startfile(file_path)
                else:
                    QMessageBox.warning(self, "文件不存在", f"文件不存在:\n{file_path}")
            else:
                QMessageBox.warning(self, "无法打开", "导出失败的文件无法打开")
    
    def open_export_folder(self):
        """打开导出文件夹"""
        current_row = self.log_table.currentRow()
        if current_row >= 0 and current_row < len(self.logs):
            log = self.logs[current_row]
            folder_path = log['file_path']
            if os.path.exists(folder_path):
                os.startfile(folder_path)
            else:
                QMessageBox.warning(self, "文件夹不存在", f"文件夹不存在:\n{folder_path}")
    
    def clear_logs(self):
        """清空日志"""
        reply = QMessageBox.question(
            self, "确认清空", 
            "确定要清空所有导出日志吗？此操作不可恢复。",
            QMessageBox.Yes | QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            try:
                # 这里需要实现清空日志的功能
                # 由于当前数据库模型没有提供清空日志的方法，这里只是提示
                QMessageBox.information(self, "提示", "清空日志功能需要数据库支持，请联系管理员")
            except Exception as e:
                QMessageBox.critical(self, "清空失败", f"清空日志失败:\n{str(e)}")
